package com.gzhryc.shared_device.iot.core.hryc;

import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.iot.core.IOTClient;
import com.gzhryc.shared_device.iot.core.IOTClientEvent;
import com.gzhryc.shared_device.iot.core.IOTMessage;
import com.gzhryc.shared_device.iot.core.enums.EIOTDeviceState;
import com.gzhryc.socket.SocketEvent;
import com.gzhryc.socket.message.MqttSocketMessage;

import java.util.Map;

public class HRYCSmartDeviceStateEvent implements IOTClientEvent {
	
	static Logger log = Logger.getLogger(HRYCSmartDeviceStateEvent.class);

	final IOTClient client;

	MqttSocketMessage mqttMsg;
	EIOTDeviceState state;		//0:离线，1:在线
	Map<String,Object> data;

	public HRYCSmartDeviceStateEvent(IOTClient client, MqttSocketMessage mqttMsg, EIOTDeviceState state) {
		this.client = client;
		this.mqttMsg = mqttMsg;
		this.state = state;
	}

	@Override
	public <T extends IOTMessage> T getMessage(Class<T> clazz) {
		if(mqttMsg != null) {
			try {
				T msg = clazz.newInstance();
				msg.setBytes(mqttMsg.getBytes());
				msg.setDeviceSn(getDeviceSn());
				msg.setTopic(mqttMsg.getTopic());
				return msg;
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public IOTMessage getMessage() {
		if(mqttMsg != null) {
			IOTMessage msg = new IOTMessage();
			msg.setBytes(mqttMsg.getBytes());
			msg.setDeviceSn(getDeviceSn());
			msg.setTopic(mqttMsg.getTopic());
			return msg;
		}
		return null;
	}

	@Override
	public IOTClient getClient() {
		return client;
	}

	@Override
	public String getDeviceSn() {
		try {
			if(this.data == null) {
				this.data = JsonTools.fromJson(mqttMsg.getString());
			}
			Object obj = this.data.get("clientid");
			if(obj != null) {
				if(obj.toString().contains("|")) {
					return obj.toString().split("\\|")[0];
				}else {
					return obj.toString();
				}
			}
		}catch(Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	@Override
	public EIOTDeviceState getState() {
		return state;
	}

	@Override
	public SocketEvent getEvent() {
		return null;
	}

}
